package com.qingsong.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.qingsong.component.MyEs;
import com.qingsong.dto.CoursePageDTO;
import com.qingsong.es.CourseDoc;
import com.qingsong.service.CourseService;
import com.qingsong.vo.CoursePageVO;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;

@CacheConfig(cacheNames = "course")
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private MyEs myEs;

    //@Cacheable(key = "#keyword", condition = "#keyword != null", unless = "#result == null")
    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", condition = "#p0 != null", unless = "#result == null")
    @Override
    public CoursePageVO<CourseDoc> search(CoursePageDTO dto) {
        int pageNumber = dto.getPageNum();
        int pageSize = dto.getPageSize();
        String keyword = dto.getKeyword();

        // 默认值
        pageNumber = ObjectUtil.isNotNull(pageNumber) ? pageNumber : 0;
        pageSize = ObjectUtil.isNotNull(pageSize) ? pageSize : 10;

        // 参数处理：//pageNum进行最小边界保护，没进ES报错，注意ES的分页是从0开始的
        pageNumber = pageNumber - 1;
        if (pageNumber < 0) pageNumber = 0;
        if (pageSize <= 0) pageSize = 0;

        // 构建查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StrUtil.isNotEmpty(keyword)) {
            MatchQueryBuilder titleQuery = QueryBuilders.matchQuery("title", keyword);
            MatchQueryBuilder authorQuery = QueryBuilders.matchQuery("author", keyword);
            boolQueryBuilder.should(titleQuery).should(authorQuery);
        }


// 执行搜索
        List<CourseDoc> searchResults = myEs.search(boolQueryBuilder, CourseDoc.class, pageNumber, pageSize);

// 计算总记录数和总页数
        long totalRow = myEs.count(boolQueryBuilder, CourseDoc.class);
        int totalPage = (int) Math.ceil((double) totalRow / pageSize);

// 组装VO并返回
        CoursePageVO<CourseDoc> result = new CoursePageVO<>();
        result.setPageNum(pageNumber);
        result.setPageSize(pageSize);
        result.setTotalRow(totalRow);
        result.setTotalPage(totalPage);
        result.setRecords(searchResults);
        return result;
    }
}